using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Diffluxum.CCScoring
{
    public class BuildFileParser : IBuildFileParser
    {
        #region IBuildFileParser Members

        BuildResult IBuildFileParser.ParseBuildFile(string fileName)
        {
            bool buildResultFound = false;

            BuildResult buildState = new BuildResult();

            using (XmlReader reader = XmlReader.Create(fileName))
            {
                reader.ReadStartElement("cruisecontrol");
                while (reader.Read() && !(buildResultFound && (buildState.ResponsibleUsers != null)))
                {
                    switch (reader.Name)
                    {
                        case "modifications":
                            buildState.ResponsibleUsers = ReadResponsible(reader.ReadSubtree());

                            break;
                        case "build":
                            buildState.BuildSuccess = ReadBuildSuccess(reader);
                            buildState.BuildDate = ReadBuildTime(reader);

                            buildResultFound = true;
                            break;
                    }
                }
            }
            return buildState;
        }

        #endregion

        private DateTime ReadBuildTime(XmlReader reader)
        {
            string buildTime = reader.GetAttribute("date");

            return DateTime.Parse(buildTime);
        }

        private bool ReadBuildSuccess(XmlReader reader)
        {
            string error = reader.GetAttribute("error");

            return (error == null) || (error != "true");
        }

        private List<string> ReadResponsible(XmlReader reader)
        {
            List<string> responsible = new List<string>();
            while (reader.ReadToFollowing("modification"))
            {
                if (!reader.ReadToFollowing("user"))
                {
                    continue;
                }

                string userName = reader.ReadElementContentAsString();
                if (!responsible.Contains(userName))
                {
                    responsible.Add(userName);
                }
            }
            return responsible;
        }
    }
}
